package com.share.trigger.job;


import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import com.share.domain.task.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时任务，补偿未能成功发送的task、线程池
 */
@Slf4j
@Component()
public class sendMessageTaskJob {
    @Resource
    private ITaskService taskService;
    @Resource
    private ThreadPoolExecutor executor;
    @Resource
    private IDBRouterStrategy dbRouter;

    @Scheduled(cron = "0/10 * * * * ?")
    public void exec(){
        try {
            //总共的库
            int dbCount = dbRouter.dbCount();
            //每个库中的task表
            for (int dbIndex = 1; dbIndex <= dbCount; dbIndex++) {
                //每个库一个线程
                int finalDbIdx = dbIndex;
                executor.execute(() -> {
                    try {
                        //
                        dbRouter.setDBKey(finalDbIdx);
                        dbRouter.setTBKey(0);
                        //查出未能成功的task
                        List<com.share.domain.task.model.TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
                        if(taskEntities.isEmpty())return;
                        for (com.share.domain.task.model.TaskEntity taskEntity : taskEntities) {
                            //线程池 发送任务
                            executor.execute(()->{
                                try {
                                    log.info("----------定时任务:发送rabbitmq消息");
                                    taskService.sendMessage(taskEntity);
                                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(),taskEntity.getMessageId());
                                }catch (Exception e){
                                    log.error("定时任务,MQ任务发送消息失败:userId:{},topic:{}",taskEntity.getUserId(),taskEntity.getTopic());
                                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(),taskEntity.getMessageId());
                                }
                            });
                        }
                    }finally {
                        dbRouter.clear();
                    }

                });
            }
        }catch (Exception e){
            log.error("定时任务,扫描MQ任务发送消息失败",e);
        }

    }

}
